package org.hepeng.workx.util;

import lombok.Builder;
import lombok.Getter;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

/**
 * @author he peng
 */
public class HttpBasicAuthUtils {

    public static boolean isBasicAuthRequest(HttpServletRequest request) {
        String header = request.getHeader("Authorization");
        if (StringUtils.startsWith(header , "Basic ")) {
            return true;
        }
        return false;
    }

    public static BasicPair extractBasicPair(HttpServletRequest request) {
        BasicPair.BasicPairBuilder basicPairBuilder = BasicPair.builder();
        String header = request.getHeader("Authorization");
        try {
            byte[] base64Token = header.substring(6).getBytes("UTF-8");
            byte[] decoded = Base64.decodeBase64(base64Token);
            String token = org.apache.commons.codec.binary.StringUtils.newStringUtf8(decoded);
            int delim = token.indexOf(":");

            if (delim == -1) {
                throw new IllegalArgumentException("Invalid basic authentication token");
            }

            basicPairBuilder.username(token.substring(0, delim)).password(token.substring(delim + 1));
        } catch (UnsupportedEncodingException e) {

        }

        return basicPairBuilder.build();
    }

    @Builder
    @Getter
    public static class BasicPair {
        private String username;
        private String password;
    }
}
